<!--
 * @Descripttion: 编辑视频
 * @Author: xiao li
 * @Date: 2020-07-06 12:17:07
 * @LastEditors: xiao li
 * @LastEditTime: 2022-01-25 10:12:33
-->
<template>
  <div class="lb-edit-card">
    <top-nav :title="navTitle" :isBack="true"></top-nav>
    <div class="page-main">
      <lb-classify-title title="视频信息"></lb-classify-title>
      <div style="height: 30px"></div>
      <el-form
        @submit.native.prevent
        :model="subForm"
        :rules="subFormRules"
        ref="aForm"
        label-width="180px"
        class="basic-form"
      >
        <el-form-item label="标题" prop="title">
          <el-input
            v-model="subForm.title"
            type="text"
            maxlength="30"
            show-word-limit
            placeholder="请输入标题"
          ></el-input>
        </el-form-item>
        <!-- v-if="!subForm.id" -->
        <el-form-item label="发布人" prop="limit_type">
          <el-radio-group
            v-model="subForm.limit_type"
            @change="redMarketChange"
          >
            <el-radio :label="0">公司</el-radio>
            <el-radio :label="1">员工</el-radio>
            <el-radio :label="2">仅员工</el-radio>
          </el-radio-group>
          <lb-tool-tips
            >可选择公司或员工，支持多选，默认不选择则为选择全部公司及员工</lb-tool-tips
          >
        </el-form-item>
        
        <el-form-item label="" prop="company" v-if="subForm.limit_type === 0">
          <el-cascader
            v-model="subForm.company"
            collapse-tags
            :options="base_company"
            @change="choiceAllCompanyItem"
            :props="{
              multiple: true,
              checkStrictly: true,
              label: 'name',
              value: 'id'
            }"
            clearable
          ></el-cascader>
        </el-form-item>
        <el-form-item label prop v-if="subForm.limit_type >= 1">
          <el-select
            v-model="subForm.staff"
            multiple
            filterable
            clearable
            collapse-tags
          >
            <el-option
              v-for="item in base_staff"
              :key="item.id"
              :label="item.name"
              :value="item.id"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="封面图" prop="cover">
          <lb-cover
            :fileList="subForm.cover"
            @selectedFiles="getCover"
          ></lb-cover>
          <lb-tool-tips>图片建议尺寸: 750 * 400</lb-tool-tips>
        </el-form-item>
        <el-form-item label="选择商品分类" prop="type">
          <el-cascader
            v-model="subForm.type"
            :options="options.cate"
            :props="defaultParams"
            clearable
          ></el-cascader>
        </el-form-item>
       <el-form-item label="标签" prop="tag">
          <el-input
            v-model.number="subForm.tag"
            placeholder="请输入标签"
          ></el-input>
        </el-form-item>
        <el-form-item label="动态密码" prop="password">
          <el-radio-group
            v-model="subForm.password"
          >
            <el-radio :label="1">是</el-radio>
            <el-radio :label="0">否</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="上传视频" prop="video">
          <div class="upload-file-warp">
            <input
              type="text"
              class="choice-file-input"
              v-model="subForm.video"
              placeholder="选择视频文件"
            />
            <lb-cover
              type="button"
              fileType="video"
              @selectedFiles="getVideo"
            ></lb-cover>
          </div>
          <lb-tool-tips
            >建议视频大小在100M以内，视频时长不超过2分钟</lb-tool-tips
          >
        </el-form-item>
        <el-form-item label="视频描述" prop="describe">
          <el-input
            type="textarea"
            :rows="4"
            v-model="subForm.describe"
            maxlength="200"
            show-word-limit
            placeholder="请输入视频描述"
          ></el-input>
        </el-form-item>
        <el-form-item label="虚拟电话数" prop="tel_num">
          <el-input
            v-model.number="subForm.tel_num"
            placeholder="请输入获取电话的虚拟数量"
          ></el-input>
        </el-form-item>
        <el-form-item label="虚拟微信数" prop="wechat_num">
          <el-input
            v-model.number="subForm.wechat_num"
            placeholder="请输入获取微信号的虚拟数量"
          ></el-input>
        </el-form-item>
        <el-form-item label="虚拟转发量" prop="send_num">
          <el-input
            v-model.number="subForm.send_num"
            placeholder="请输入虚拟转发量"
          ></el-input>
        </el-form-item>
        <el-form-item label="关联商品" prop v-if="is_shop">
          <el-tag
            :closable="cur_info.goods.name ? true : false"
            @close="delCurInfo(1)"
            @click="chooseCurInfo(1)"
            >{{ cur_info.goods.name || '选择商品' }}</el-tag
          >
        </el-form-item>
        <el-form-item label="关联优惠" prop v-if="is_quan">
          <el-tag
            :closable="cur_info.quan.name ? true : false"
            @close="delCurInfo(2)"
            @click="chooseCurInfo(2)"
            >{{ cur_info.quan.name || '选择优惠' }}</el-tag
          >
        </el-form-item>
        <el-form-item label="排序值" prop="top">
          <el-input-number
            class="lb-input-number"
            v-model="subForm.top"
            :controls="false"
            :precision="0"
            :min="0"
            placeholder="请输入排序值"
          ></el-input-number>
          <lb-tool-tips>值越大, 排序越靠前</lb-tool-tips>
        </el-form-item>
        <el-form-item>
          <lb-button @click="submitFormInfo" type="primary">{{
            $t('action.save')
          }}</lb-button>
          <lb-button @click="goBack">{{ $t('action.back') }}</lb-button>
        </el-form-item>
      </el-form>

      <el-dialog
        title="选择可用商品"
        :visible.sync="chooseDialog"
        width="800px"
        :close-on-click-modal="false"
        :close-on-press-escape="false"
        :append-to-body="true"
        :before-close="beforeClose"
      >
        <div class="dialog-link-box">
          <div class="link-right" :style="{ width: '100%' }">
            <el-form
              @submit.native.prevent
              :inline="true"
              :model="searchForm.goods"
            >
              <el-form-item label>
                <el-input
                  v-model="searchForm.goods.name"
                  placeholder="请输入名称"
                ></el-input>
              </el-form-item>
              <lb-button type="primary" @click="handleCurrentChange(1)">{{
                $t('action.search')
              }}</lb-button>
            </el-form>
            <el-table
              v-loading="loading"
              :data="tableData.goods"
              ref="singleTable"
              highlight-current-row
              @current-change="handleCurrentRow"
              style="width: 100%"
            >
              <el-table-column prop="id" label="ID"></el-table-column>
              <el-table-column prop="name" label="商品名称"></el-table-column>
              <el-table-column prop="cover" label="封面图">
                <template slot-scope="scope">
                  <lb-image :src="scope.row.cover[0]" />
                </template>
              </el-table-column>
              <el-table-column
                prop="cate_text"
                label="所属分类"
              ></el-table-column>
              <el-table-column prop="price_text" label="价格"></el-table-column>
              <el-table-column
                prop="sale_count"
                label="累计净销量"
              ></el-table-column>
              <el-table-column prop="stock" label="库存"></el-table-column>
            </el-table>
          </div>
        </div>
        <lb-page
          :batch="false"
          :page="searchForm.goods.page"
          :pageSize="searchForm.goods.limit"
          :total="total.goods"
          @handleSizeChange="handleSizeChange"
          @handleCurrentChange="handleCurrentChange"
        ></lb-page>

        <div style="text-align: right; margin-top: 20px">
          <el-button @click="chooseDialog = false">取 消</el-button>
          <el-button type="primary" @click="handleConfirm">确 定</el-button>
        </div>
      </el-dialog>

      <el-dialog
        title="选择可用优惠"
        :visible.sync="chooseQuanDialog"
        width="800px"
        :close-on-click-modal="false"
        :close-on-press-escape="false"
        :append-to-body="true"
        :before-close="beforeQuanClose"
      >
        <div class="dialog-link-box">
          <div class="link-left">
            <div
              @click="toChange(index)"
              class="left-item"
              :class="[{ 'left-active': curQuanIndex === index }]"
              v-for="(item, index) in quanList"
              :key="index"
            >
              {{ item.title }}
            </div>
          </div>
          <div class="link-right" :style="{ width: '600px' }">
            <el-form
              @submit.native.prevent
              :inline="true"
              :model="searchForm.quan"
            >
              <el-form-item label>
                <el-input
                  v-model="searchForm.quan.title"
                  placeholder="请输入标题名称"
                ></el-input>
              </el-form-item>
              <lb-button type="primary" @click="handleCurrentChange(1)">{{
                $t('action.search')
              }}</lb-button>
            </el-form>
            <!-- curQuanType 1带客有礼；2新客福包；3满减返佣 -->
            <!-- {{curQuanType}} -->
            <el-table
              v-loading="loading"
              :data="tableData.quan"
              ref="singleTable"
              highlight-current-row
              @current-change="handleCurrentRow"
              style="width: 100%"
            >
              <el-table-column
                prop="id"
                label="ID"
                width="180"
              ></el-table-column>
              <el-table-column prop="title" label="标题"></el-table-column>
            </el-table>
          </div>
        </div>
        <lb-page
          :batch="false"
          :page="searchForm.quan.page"
          :pageSize="searchForm.quan.limit"
          :total="total.quan"
          @handleSizeChange="handleSizeChange"
          @handleCurrentChange="handleCurrentChange"
        ></lb-page>

        <div style="text-align: right; margin-top: 20px">
          <el-button @click="chooseQuanDialog = false">取 消</el-button>
          <el-button type="primary" @click="handleConfirm">确 定</el-button>
        </div>
      </el-dialog>
    </div>
  </div>
</template>

<script>
import { post } from '../../../api/index'
export default {
  data () {
    return {
      navTitle: '',
      loading: false,
      curChoose: 1,
      curQuanIndex: 0,
      curQuanType: -1,
      cur_info: {
        goods: {
          id: '',
          name: ''
        },
        quan: {
          id: '',
          name: ''
        }
      },
      currentRow: {},
      chooseDialog: false,
      chooseQuanDialog: false,
      tableData: {
        quan: [],
        goods: []
      },
      is_shop: false,
      is_quan: false,
      quanList: [],
      total: {
        quan: 0,
        goods: 0
      },
      searchForm: {
        quan: {
          page: 1,
          limit: 10,
          title: ''
        },
        goods: {
          page: 1,
          limit: 10,
          name: ''
        }
      },
      base_company: [],
      companyResult: [],
      form: {
        copyCompanyId: []
      },
      base_staff: [],
      // 基本信息
      subForm: {
        id: '',
        limit_type: 0,
        password:0,
        all_company: 1,
        company: [],
        staff: [],
        title: '',
        type:'',
        cover: '',
        video: '',
        describe: '',
        tel_num: '',
        wechat_num: '',
        tag:'',
        send_num: '',
        goods: [],
        top: 0,
        
        preferential_id: 0,
        preferential_type: 0
      },
       // 树状单选下拉框配置
      defaultParams: {
        checkStrictly: true,
        label: 'title',
        value: 'id'
      },
      options: {},
      subFormRules: {
        title: {
          required: true,
          type: 'string',
          message: '请输入标题',
          trigger: 'blur'
        },
        limit_type: {
          required: true,
          type: 'number',
          message: '请选择发布人',
          trigger: 'blur'
        },
        cover: {
          required: true,
          type: 'array',
          message: '请选择视频封面图',
          trigger: 'blur'
        },
        video: {
          required: true,
          type: 'string',
          message: '请选择上传视频',
          trigger: 'blur'
        },
        describe: {
          required: true,
          type: 'string',
          message: '请输入视频描述',
          trigger: 'blur'
        }
      }
    }
  },
  async created () {
    setTimeout(() => {
      console.log(this.parimarOptions)
    }, 10000)
    await this.getSelectOptions()
    let { id } = this.$route.query
    this.navTitle = this.$t(id ? 'menu.ShortVideoEdit' : 'menu.ShortVideoAdd')
    await Promise.all([this.getBaseCompany(), this.getBaseStaffInfo(), this.getGoodsList(), this.getDiscountList()])
    if (id) {
      this.id = id
      await this.getDetail(id)
    }
  },
  methods: {
    async getDetail (id) {
      let { code, data } = await this.$api.shortvideoUpdate({ id })
      if (code !== 200) return
      data.info.cover = [{ url: data.info.cover }]
      data.info.company = data.company || []
      data.info.staff = data.staff || []
      for (let key in this.subForm) {
        if(key == "password"){
          this.subForm[key] = !!data.info[key] ? 1:0;
        }else{
          this.subForm[key] = data.info[key]
        }
      }
      if (data.goods_list.length > 0) {
        let { id, name } = data.goods_list[0]
        this.cur_info.goods = { id, name }
      }
      if (data.info.preferential_id) {
        let { name } = data.info.preferential_info
        let id = data.info.preferential_id
        let type = data.info.preferential_type
        this.cur_info.quan = { id, name, type }
      }
    },
    getSelectOptions () {
      this.$api.GoodsListSelect().then(res => {
        if (res.code === 200) {
          let { data } = res
          this.handleCompanyOptions(data.company)
          data.company.length &&
            data.company.unshift({
              id: 0,
              name: '全选'
            })
          this.options = data
        }
      })
    },
    handleCurrentRow (e) {
      this.currentRow = e
    },
    handleConfirm () {
      let { id = 0, name = '', title = '' } = this.currentRow
      if (!id) return
      let key = this.curChoose === 1 ? 'goods' : 'quan'
      this.cur_info[key] =
        this.curChoose === 1
          ? { id, name }
          : { id, name: title, type: this.quanList[this.curQuanIndex].type }
      this.currentRow = {}
      this.chooseDialog = false
      this.chooseQuanDialog = false
    },
    beforeClose () {
      let key = this.curChoose === 1 ? 'goods' : 'quan'
      this.currentRow = {}
      this.curQuanIndex = 0
      this.curQuanType = this.quanList.length > 0 ? this.quanList[0].type : ''
      this.total[key] = 0
      this.tableData[key] = []
      this.searchForm = {
        quan: {
          page: 1,
          limit: 10,
          title: ''
        },
        goods: {
          page: 1,
          limit: 10,
          name: ''
        }
      }
      this.chooseDialog = false
      this.chooseQuanDialog = false
    },
    delCurInfo (type) {
      let key = type === 1 ? 'goods' : 'quan'
      this.cur_info[key] =
        type === 1 ? { id: '', name: '' } : { id: '', name: '', type: '' }
    },
    async chooseCurInfo (type) {
      this.curChoose = type
      if (type === 1) {
        this.getGoodsList(1)
        this.chooseDialog = true
      } else if (type === 2) {
        await this.getDiscountList()
        await this.getQuanList()
        this.chooseQuanDialog = true
      }
    },
    async getDiscountList () {
      let { code, data } = await this.$api.shortvideoDiscount()
      this.loading = false
      if (code !== 200) return
      this.quanList = data
      this.is_quan = data.length > 0
    },
    toChange (index) {
      this.curQuanIndex = index
      this.curQuanType = this.quanList[index].type
      this.tableData.quan = []
      this.handleCurrentChange(1)
    },
    handleSizeChange (val) {
      let key = this.curChoose === 1 ? 'goods' : 'quan'
      this.searchForm[key].limit = val
      this.handleCurrentChange(1)
    },
    handleCurrentChange (val) {
      let key = this.curChoose === 1 ? 'goods' : 'quan'
      if (val === 1) {
        this.tableData[key] = []
      }
      this.searchForm[key].page = val
      if (this.curChoose === 1) {
        this.getGoodsList()
      } else {
        this.getQuanList()
      }
    },
    async getQuanList (flag) {
      if (flag) {
        this.searchForm.quan.page = 1
        this.tableData.quan = []
      }
      this.loading = true
      let { quan } = this.searchForm
      let { api_path: methodModel, type } = this.quanList[this.curQuanIndex]
      this.curQuanType = type
      let { code, data } = await post(methodModel, quan)
      this.loading = false
      if (code !== 200) return
      this.tableData.quan = data.data
      this.total.quan = data.total
    },
    async getGoodsList (flag) {
      if (flag) {
        this.searchForm.goods.page = 1
        this.tableData.goods = []
      }
      this.loading = true
      let { goods } = this.searchForm
      let { code, data } = await this.$api.shortvideoConfig(goods)
      this.loading = false
      if (code !== 200) return
      this.is_shop = data.shop
      this.tableData.goods = data.goods_list.data
      this.total.goods = data.goods_list.total
    },
    async getBaseStaffInfo (name) {
      let { data } = await this.$api.getBaseStaffInfo({
        name
      })
      this.base_staff = data
    },
    async getBaseCompany () {
      // 基本信息验证
      let { data: company } = await this.$api.getBaseCompany()
      this.handleCompanyOptions(company)
      this.base_company = company
    },
    handleCompanyOptions (data, arr = []) {
      for (let i = 0, len = data.length; i < len; i++) {
        let newArr = JSON.parse(JSON.stringify(arr))
        newArr.push(data[i].id)
        this.companyResult.push(JSON.parse(JSON.stringify(newArr)))
        if (data[i].children && data[i].children.length) {
          this.handleCompanyOptions(data[i].children, newArr)
        }
      }
    },
    /**
     * @method 全选公司
     */
    choiceAllCompanyItem (val) {
      let { companyResult } = this
      // true = 添加  false 取消、减少
      let rType = val.length > this.form.copyCompanyId.length
      let firstVal = val[0] && val[0][0]
      if (rType) {
        // 添加
        if (firstVal && val.length === companyResult.length) {
          // 其他都选完了，就只有全选没选了
          this.subForm.company = [[0], ...val]
        } else if (firstVal === 0) {
          this.subForm.company = [[0], ...companyResult]
        }
      } else {
        // 减少
        if (firstVal === 0) {
          // 第一个为0 只取消全选
          let copyArr = JSON.parse(JSON.stringify(val))
          copyArr.splice(0, 1)
          this.subForm.company = copyArr
        } else if (val.length === companyResult.length) {
          // 清空
          this.subForm.company = []
        } else {
          this.subForm.company = val
        }
      }
      this.form.copyCompanyId = this.subForm.company
    },
    getCover (e) {
      this.subForm.cover = e
    },
    getVideo (e) {
      this.subForm.video = e[0].url
    },
    goBack () {
      this.$router.back(-1)
    },
    async submitFormInfo () {
      let subForm = JSON.parse(JSON.stringify(this.subForm))
      let formArr = ['aForm']
      //alert(JSON.stringify(this.subForm))
      let flag = true
      for (let i = 0, len = formArr.length; i < len; i++) {
        this.$refs[formArr[i]].validate(valid => {
          if (!valid) {
            flag = false
            return false
          }
        })
      }
      if (flag) {
        subForm.company = subForm.limit_type === 0 ? subForm.company : []
        subForm.staff = subForm.limit_type >= 1 ? subForm.staff : []
        subForm.all_company = (subForm.limit_type === 0 && subForm.company.length < 1) || (subForm.limit_type >= 1 && subForm.staff.length < 1) ? 1 : 0
        subForm.cover = subForm.cover[0].url
        subForm.goods = this.cur_info.goods.id ? [this.cur_info.goods.id] : []
        subForm.preferential_id = this.cur_info.quan.id || 0
        subForm.preferential_type = this.cur_info.quan.type || 0
        let methodModel = subForm.id ? 'shortvideoUpdate' : 'shortvideoAdd'
        let { code } = await this.$api[methodModel](subForm)
        if (code !== 200) return
        this.$message.success(this.$t('tips.successSub'))
        this.goBack()
      }
    }
  }
}
</script>

<style lang="scss" scoped>
.lb-edit-card {
  width: 100%;
  .el-input,
  .el-select,
  .lb-input-number,
  .el-cascader,
  .el-textarea {
    width: 400px;
  }
}

/* 选择弹窗 */
.dialog-link-box {
  width: 100%;
  height: auto;
  display: flex;
  flex-wrap: wrap;
  .link-left {
    height: 100%;
    .left-item {
      width: 120px;
      height: 35px;
      color: #666;
      font-size: 14px;
      background: #f4f6f8;
      display: flex;
      align-items: center;
      justify-content: center;
      margin-right: 20px;
      border-bottom: 1px solid white;
    }
    .left-item.left-active {
      background: #409eff;
      color: white;
    }
  }
  .link-right {
    height: 100%;
  }
}
.dialog-footer {
  display: flex;
  align-items: center;
}
</style>
